<template>
  <textarea id="tinymce" v-model="content"></textarea>
</template>

<script>
import tinymce from "tinymce/tinymce";
import theme from "tinymce/themes/silver/theme";
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/preview";
import request from "@/utils/request";
export default {
  data() {
    return {
      edit: null,
      innerHTML: "",
      uploadUrl: process.env.VUE_APP_EDITOR_UPLOAD_URL,

      setContent: true
    };
  },
  props: {
    content: {
      type: String,
      default: ""
    },
    height: {
      type: Number,
      default: 300
    }
  },
  model: {
    prop: "content"
  },
  watch: {
    content: function() {
      if (this.setContent) {
        tinymce.activeEditor.setContent(this.content);
        this.setContent = false;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.edit = tinymce.init({
        selector: "#tinymce",
        language_url: "/static/tinymce/langs/zh_CN.js",
        skin_url: "/static/tinymce/skins",
        content_css: "/static/tinymce/skins/content/default/content.min.css",
        language: "zh_CN",
        theme_url: theme,
        height: this.height,
        relative_urls: false,
        image_dimensions: false,
        plugins: "link lists image code table preview",
        toolbar:
          "bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image | removeformat",
        branding: false,
        init_instance_callback: editor => {
          editor.on("Change", () => {
            this.$emit("input", editor.getContent());
          });
        },
        images_upload_handler: (blobInfo, success, failure) => {
          // 图片异步上传处理函数
          this.handler(blobInfo, success, failure);
        }
      });
    });
  },
  beforeDestroy() {
    tinymce.remove(this.editor);
  },
  methods: {
    handler(blobInfo, success, failure) {
      let formdata = new FormData();
      formdata.append("img", blobInfo.blob());
      request({
        url: this.uploadUrl,
        method: "post",
        data: formdata
      })
        .then(res => {
          if (res.code === 1) {
            success(res.data.url);
          } else {
            failure(res.msg);
          }
        })
        .catch(() => {
          failure("文件上传失败，请联系管理员");
        });
    }
  }
};
</script>

<style scoped></style>
